<template>
  <div class="container_index">
    <div class="content">
      <div class="content_left">
        <div
          class=""
          style="
            width: 100%;
            height: 200px;
            background: #ffffff;
            border-radius: 16px;
            -webkit-box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
            box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
          "
        >
          <div
            style="width: 100%; height: 100%"
            v-if="info.lastTaskInfo == null"
            class="flexColCenter flexCen"
          >
            <el-empty
              style="transform: scale(0.7)"
              description="暂无学习纪录~"
            ></el-empty>
          </div>

          <div v-else class="content_left_top">
            <el-image
              :src="
                info.lastTaskInfo.coursePic ? info.lastTaskInfo.coursePic : ''
              "
              class="top_img"
            ></el-image>
            <div class="top_mid">
              <div class="top_mid_title overTxt">
                {{
                  info.lastTaskInfo
                    ? info.lastTaskInfo.ancestorsName[0]
                    : '暂无'
                }}
              </div>
              <div class="top_mid_content overTxt mt_16">
                {{
                  info.lastTaskInfo
                    ? info.lastTaskInfo.ancestorsName[1]
                    : '暂无'
                }}
              </div>
              <div class="top_mid_content overTxt mt_6">
                {{
                  info.lastTaskInfo
                    ? info.lastTaskInfo.ancestorsName[2]
                    : '暂无'
                }}
              </div>
              <div class="top_mid_time mt_16">
                {{ parseTime(info.lastTaskInfo.lastStudyTime) }}
              </div>
            </div>
            <div @click="goStudy" class="top_right">继续学习</div>
          </div>
        </div>
        <div class="content_left_mid">
          <div class="title_mid">每日完成内容</div>
          <div class="dailyCompletion" ref="dailyCompletion"></div>
        </div>
        <div class="content_left_bottom">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <!-- 消息 -->
            <el-tab-pane label="未读消息" name="1">
              <div v-if="messageList.length > 0" class="unread_item_scroll">
                <div
                  @click="readMsg('message', item)"
                  class="unread_item shou"
                  v-for="(item, index) in messageList"
                  :key="index"
                >
                  <div style="width: 600px">{{ item.title }}</div>
                  <div>{{ parseTime(item.createTime) }}</div>
                </div>
              </div>
              <div v-if="messageList.length == 0" class="unread_item_scroll">
                <el-empty
                  style="transform: scale(0.7); height: calc(100vh - 700px)"
                  description="暂无消息~"
                ></el-empty>
              </div>
            </el-tab-pane>
            <!-- 通知 -->
            <el-tab-pane label="通知" name="2">
              <div v-if="messageList.length > 0" class="unread_item_scroll">
                <div
                  @click="readMsg('notice', item)"
                  class="unread_item shou"
                  v-for="(item, index) in messageList"
                  :key="index"
                >
                  <div style="width: 600px" v-html="item.noticeTitle"></div>
                  <div>{{ parseTime(item.createTime) }}</div>
                </div>
              </div>
              <div v-if="messageList.length == 0" class="unread_item_scroll">
                <el-empty
                  style="transform: scale(0.7); height: calc(100vh - 700px)"
                  description="暂无消息~"
                ></el-empty>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="content_right">
        <div class="content_right_top">
          <div class="user_info">
            <div
              v-if="!avatar.includes('http')"
              class="user_info_img_div"
              :style="{
                'background-color': avatar,
              }"
            >
              {{ getLastTwoCharacters(user.nickName) }}
            </div>
            <img
              v-if="avatar.includes('http')"
              class="user_info_img"
              :src="avatar"
              alt="加载失败"
            />
            <div class="user_info_right">
              <div class="salutation">{{ getAmPm() }}{{ user.nickName }}</div>
              <div class="user_info_detail">
                <span>学号：{{ user.studentNum }}</span> <span> | </span>
                <span>班级：{{ user.className }}</span>
              </div>
            </div>
          </div>
          <div class="conclusion">
            昨日完成{{ info.finishTaskCountYesterday }}内容，超过本校{{
              info.finishTaskCountYesterdayPercent
            }}%同学
          </div>
        </div>
        <div class="content_right_bottom">
          <el-calendar class="calendar" v-model="value">
            <template slot="dateCell" slot-scope="{ data }">
              <div class="relative" :class="data.isSelected ? 'choseDay' : ''">
                <span>{{
                    data.day == getToday() ? '今' : data.day.slice(8)
                  }}</span>
                <div
                  v-if="data.day == getToday()"
                  class="point"
                  :class="data.isSelected ? 'site' : ''"
                ></div>
              </div>
            </template>
          </el-calendar>
        </div>
      </div>
      <!--  消息弹框    -->
      <messageShow
        :open.sync="MsgOpen"
        :title="MsgTitle"
        :item="MsgItem"
      ></messageShow>
    </div>
  </div>
</template>

<script>
import { getLastTwoCharacters } from '@/utils/util.js'
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
import { studentInfo } from '@/api/mine/mine'
import { homepage, daily } from '@/api/home'
import { getMyMessageList } from '@/api/home/message'
import { updatePost_readmessage } from '@/api/home/message'
import messageShow from '@/components/messageShow.vue'

export default {
  name: 'newIndex',
  components: {
    messageShow
  },
  data() {
    return {
      getLastTwoCharacters: function(name) {
        return getLastTwoCharacters(name)
      },
      // ---------消息显示组件----------
      MsgOpen: false,
      MsgTitle: '',
      MsgItem: {},
      title: '',
      keyId: '',
      showScoreDialog: false,
      msgId: '',
      scoreInfo: {
        score: '',
        sameScore: '',
        paperType: 1,
        groupMemberList: []
      },
      // --------------=---
      dateList: [],
      studentFinishTaskCountData: [],
      classFinishTaskCountData: [],
      activeName: '1',
      value: new Date(),

      //触底加载更多
      upLoadData: [],
      messageList: [],
      totalPage: 0,
      total: 0,
      pageModel: {
        pageNum: 1,
        pageSize: 10
      },
      user: {},
      info: {
        lastTaskInfo: {
          ancestorsName: [],
          coursePic: '',
          lastStudyTime: ''
        },
        finishTaskCountYesterday: 0,
        finishTaskCountYesterdayPercent: 0
      }
    }
  },
  watch: {
    activeName: {
      handler(val) {
        if (val == '1') {
          this.getMessageList()
        } else {
          this.getMessageList(3)
        }
      }
    }
  },
  mounted() {
    this.getInfo()
    this.getMessageList()
  },
  computed: {
    ...mapGetters(['currentCourse', 'avatar'])
  },
  methods: {
    getAmPm() {
      let now = new Date()
      let hours = now.getHours()
      let minutes = now.getMinutes()
      return hours > 12 || (hours === 12 && minutes > 0) ? '下午好！' : '上午好！'
    },
    goStudy() {
      this.$router.push({
        path: '/taskList',
        query: {
          courseId: this.info.lastTaskInfo.courseId,
          indexId: this.info.lastTaskInfo.indexId,
          courseStuId: this.info.lastTaskInfo.courseStuId,
          courseSchedulingId: this.info.lastTaskInfo.courseSchedulingId
        }
      })
    },
    /* 已读 */
    async readMsg(type, item) {
      if (type == 'notice') {
        await updatePost_readmessage(item.id)
        this.MsgOpen = true
        this.MsgItem = item
        this.MsgTitle = '通知'
        this.getMessageList(3)
      } else {
        //item.msgType 8 组长评分   9  自评
        this.keyId = item.keyId
        this.msgId = item.id
        if (item.msgType == 8 || item.msgType == 9 || item.msgType == 10) {
          // msgType: 8 --> 考核互评   9 --> 考核自评
          // approvalType  1-师评 2-组长评分(互评) 3-自评 4-组间互评
          let obj = {
            8: '2',
            9: '3',
            10: '4'
          }
          this.$router.push({
            path: '/approvalAnswer',
            query: { keyId: item.keyId, userId: item.senderId, routeSign: 'stu', approvalType: obj[item.msgType], leaderId: item.remark }
          })
        } else if (item.msgType == 1) {
          await updatePost_readmessage(item.id)
          this.$router.push({ path: '/answerExam', query: { id: item.keyId, type: 1, studyRecordId: item.remark } })
        } else if (item.msgType == 0) {
          await updatePost_readmessage(item.id)
          this.$router.push({ path: '/examDetail', query: { id: item.keyId } })
        } else {
          await updatePost_readmessage(item.id)
          this.MsgOpen = true
          this.MsgItem = item
          this.MsgTitle = '消息'
          this.getMessageList()
        }
      }
    },
    /* 获取个人资料 */
    async getInfo() {
      let [res1, res2, res3] = await Promise.all([
        homepage(),
        daily(),
        studentInfo()
      ])
      this.user = res3.data
      this.classFinishTaskCountData =
        res2.data.studentFinishTaskCountData.series[0].data
      this.studentFinishTaskCountData =
        res2.data.classFinishTaskCountData.series[0].data
      this.dateList = res2.data.classFinishTaskCountData.xAxis.data
      this.setOptionCdn()
      res1.data.lastTaskInfo
        ? (res1.data.lastTaskInfo.ancestorsName = res1.data.lastTaskInfo
          ? res1.data.lastTaskInfo.ancestorsName.split('/')
          : [])
        : null
      this.info = res1.data
    },
    async getMessageList(msgType) {
      this.messageList = []
      try {
        //sort
        let params = {
          type: 1,
          sort: 0,
          readStatus: 0,
          pageNum: 1,
          pageSize: 99999
        }
        if (msgType) {
          params.type = msgType
        }
        let res = await getMyMessageList(params)
        const { code, data } = res
        if (code == 200) {
          if (msgType == 3) {
            if (data.noticeList.length > 0) {
              data.noticeList.map((item) => {
                item.noticeFiles = JSON.parse(item.noticeFiles)
              })
              this.messageList = data.noticeList
            }
          } else {
            this.messageList = data.messageList
          }
          let allUnRead =
            data.unReadCourseMessageNum +
            data.unReadPersonalMessageNum +
            data.unReadNoticeNum
          this.$EventBus.$emit('refresh', allUnRead)
        }
      } catch (e) {
        console.error(e)
      }
    },
    getToday() {
      let currentDate = new Date()
      // 获取年、月、日
      let year = currentDate.getFullYear()
      let month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
      let day = currentDate.getDate().toString().padStart(2, '0')
      // 格式化日期
      return year + '-' + month + '-' + day
    },
    handleClick(tab) {
      this.activeName = tab.name
    },
    setOptionCdn() {
      let myChart = echarts.init(this.$refs.dailyCompletion)
      let option
      option = {
        color: ['#e925b5', '#46dfff'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              color: '#666666',
              backgroundColor: 'white'
            }
          }
        },
        legend: {
          right: '3%',
          data: ['个人完成内容数量', '班级平均完成内容数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.dateList,
            boundaryGap: false, // 不留白，从原点开始
            axisLine: {
              lineStyle: {
                type: 'solid',
                color: '#f6f7f9', //左边线的颜色
                width: '1' //坐标线的宽度
              }
            },
            axisLabel: {
              textStyle: {
                color: '#666666' //坐标值得具体的颜色
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
            axisLine: {
              lineStyle: {
                type: 'solid',
                color: '#f6f7f9', //左边线的颜色
                width: '1' //坐标线的宽度
              }
            },
            axisLabel: {
              formatter: '{value}', //显示数据带上h
              textStyle: {
                color: '#666666' //坐标值得具体的颜色
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#f6f7f9'],
                width: 1,
                type: 'solid'
              }
            } //去除网格线
          }
        ],
        series: [
          {
            name: '个人完成内容数量',
            type: 'line',
            symbol: 'none',
            smooth: true,
            lineStyle: {
              width: 2
            },
            itemStyle: {
              normal: {
                label: {
                  show: false,
                  position: 'top',
                  textStyle: {
                    color: '#e925b5',
                    fontsize: '16'
                  },
                  formatter: '{c}' //显示数据带上h
                }
              }
            },
            emphasis: {
              focus: 'series'
            },
            data: this.classFinishTaskCountData
          },
          {
            name: '班级平均完成内容数量',
            type: 'line',
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 2
            },
            itemStyle: {
              normal: {
                label: {
                  show: false,
                  position: 'top',
                  textStyle: {
                    color: '#46dfff',
                    fontsize: '16'
                  },
                  formatter: '{c}' //显示数据带上h
                }
              }
            },
            emphasis: {
              focus: 'series'
            },
            data: this.studentFinishTaskCountData
          }
        ]
      }
      option && myChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
.userInfo-avatar-div {
  margin: 17px 16px 0 24px;
  border: 1px solid #eeeeee;
  width: 40px;
  height: 40px;
  border-radius: 20px;
  text-align: center;
  line-height: 38px;
  font-size: 20px;
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 600;
  color: #ffffff;
}

.container_index {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.content {
  margin-top: 18px;
  width: 1360px;
  display: flex;
}

.content_left {
  width: 840px;
}

.content_left_top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px 41px 26px 32px;
  box-sizing: border-box;

  .top_img {
    width: 226px;
    height: 142px;
    border-radius: 8px;
  }

  .top_mid {
    flex: 1;
    height: 100%;
    margin-left: 24px;

    .top_mid_title {
      width: 400px;
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
      font-weight: 600;
      color: #333333;
    }

    .top_mid_content {
      width: 400px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #333333;
    }

    .top_mid_time {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #999999;
    }
  }

  .mt_16 {
    margin-top: 16px;
  }

  .mt_6 {
    margin-top: 6px;
  }

  .top_right {
    width: 100px;
    height: 40px;
    border-radius: 20px;
    border: 1px solid #28b28b;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #28b28b;
    cursor: pointer;
    user-select: none;
  }

  .top_right:hover {
    background: #28b28b;
    color: white;
  }

  .top_right:active {
    background: #259776;
    color: white;
  }
}

.content_left_mid {
  position: relative;
  margin-top: 16px;
  width: 100%;
  height: 290px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
  padding: 32px;
  box-sizing: border-box;
}

.title_mid {
  position: absolute;
  top: 32px;
  left: 32px;
  font-size: 20px;
  font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
  font-weight: 600;
  color: #333333;
}

.content_left_bottom {
  margin-top: 16px;
  width: 100%;

  height: calc(100vh - 627px);
  background: #ffffff;
  border-radius: 16px;
  padding: 12px 32px;
  box-sizing: border-box;
  box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);

  .unread_item_scroll {
    width: 100%;
    height: calc(100vh - 700px);
    overflow: auto;

    .unread_item {
      box-sizing: border-box;
      width: 100%;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC, sans-serif;
      font-weight: 400;
      color: #999999;
      border-bottom: 1px solid #edeff0;
      display: flex;
      justify-content: space-between;
      padding: 0 10px 16px 0;
      margin-top: 16px;
    }
  }
}

.content_right {
  margin-left: 16px;
  width: 504px;
}

.content_right_top {
  width: 100%;
  height: 200px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);
  padding: 32px;
  box-sizing: border-box;

  .user_info {
    display: flex;
    align-items: center;

    .user_info_img_div {
      border: 1px solid #eeeeee;
      width: 60px;
      height: 60px;
      border-radius: 30px;
      text-align: center;
      line-height: 58px;
      font-size: 22px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      color: #ffffff;
    }

    .user_info_img {
      width: 60px;
      height: 60px;
    }

    .user_info_right {
      margin-left: 24px;

      .salutation {
        font-size: 24px;
        font-family: PingFangSC-Semibold, PingFang SC, sans-serif;
        font-weight: 600;
        color: #333333;
      }

      .user_info_detail {
        margin-top: 7px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC, sans-serif;
        font-weight: 400;
        color: #999999;
      }
    }
  }

  .conclusion {
    font-size: 18px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #333333;
    margin-top: 22px;
  }
}

.content_right_bottom {
  padding: 40px 20px;
  box-sizing: border-box;
  margin-top: 16px;
  width: 100%;
  height: calc(100vh - 321px);
  overflow: auto;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: inset 0 0 5px rgba(97, 184, 179, 0.1);

  .calendar {
    width: 100%;
    height: 100%;
  }
}

.dailyCompletion {
  width: 100%;
  height: 100%;
}

::v-deep .el-tabs__header {
  margin: 0 !important;
}

//日历样式>>>>>>>>>>>>>>>>start
::v-deep .el-calendar-table .el-calendar-day {
  width: 50px !important;
  height: 50px;
  padding: 0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 8px 0 8px 4px;
}

::v-deep .el-calendar-table td.is-selected {
  width: 50px;
  border-radius: 50%;
  background: transparent;
}

::v-deep .el-calendar-table td {
  border: 0;
  border-radius: 50%;
}

::v-deep .el-calendar-table tr {
  margin: 10px 0;
}

::v-deep .el-calendar-table tr td:first-child {
  border-left: 0;
}

::v-deep .el-calendar-table tr:first-child td {
  border-top: 0;
}

::v-deep .el-calendar-table td {
  width: 50px;
}

.choseDay {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  text-align: center;
  line-height: 50px;
  background: #28b28b;
  color: white;
}

.point {
  position: absolute;
  width: 6px;
  height: 6px;
  background: #47e3ec;
  border-radius: 50%;
  top: 22px;
  left: 7px;
}

.relative {
  position: relative;
}

.site {
  top: 36px !important;
  left: 22px !important;
}

//日历样式>>>>>>>>>>>>>>>>end

.item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .label {
    font-size: 14px;
    color: #939393;
  }

  .value {
    width: 300px;
    color: #333333;
    margin-left: 10px;
  }
}
</style>
